"""
完整自动化滑动脚本
功能：
1. 支持自定义滑动间隔和次数
2. 支持指定应用包名（可选启动应用）
3. 记录滑动日志
4. 异常处理和重连机制
"""

from ppadb.client import Client
import time
import argparse
from datetime import datetime

class PhoneAutomation:
    def __init__(self, interval=5, total_count=None, app_package=None):
        """
        初始化自动化控制器
        
        参数：
        interval: 滑动间隔（秒）
        total_count: 总滑动次数（None=无限次）
        app_package: 应用包名（可选）
        """
        self.interval = interval
        self.total_count = total_count
        self.app_package = app_package
        self.device = None
        self.count = 0
        
    def connect_device(self):
        """连接设备"""
        try:
            adb = Client(host="127.0.0.1", port=5037)
            devices = adb.devices()
            
            if len(devices) == 0:
                print("❌ 未检测到设备")
                return False
            
            self.device = devices[0]
            print(f"✅ 已连接设备: {self.device.serial}")
            return True
            
        except Exception as e:
            print(f"❌ 连接失败: {e}")
            return False
    
    def start_app(self):
        """启动指定应用（如果配置了包名）"""
        if not self.app_package:
            return
        
        try:
            # 启动应用
            self.device.shell(f"monkey -p {self.app_package} -c android.intent.category.LAUNCHER 1")
            print(f"📱 已启动应用: {self.app_package}")
            time.sleep(2)  # 等待应用启动
        except Exception as e:
            print(f"⚠️  启动应用失败: {e}")
    
    def swipe_up(self):
        """执行向上滑动"""
        try:
            self.device.shell("input swipe 500 1500 500 500 300")
            self.count += 1
            current_time = datetime.now().strftime('%H:%M:%S')
            print(f"[{self.count}] {current_time} ✅ 滑动成功")
            return True
        except Exception as e:
            print(f"❌ 滑动失败: {e}")
            return False
    
    def should_continue(self):
        """判断是否继续执行"""
        if self.total_count is None:
            return True
        return self.count < self.total_count
    
    def run(self):
        """运行自动化任务"""
        if not self.connect_device():
            return
        
        self.start_app()
        
        print(f"\n⏰ 滑动间隔: {self.interval} 秒")
        if self.total_count:
            print(f"🎯 目标次数: {self.total_count} 次")
        else:
            print(f"🔄 持续运行（按 Ctrl+C 停止）")
        print("-" * 50)
        
        try:
            while self.should_continue():
                if not self.swipe_up():
                    # 滑动失败，尝试重连
                    print("🔄 尝试重新连接...")
                    if not self.connect_device():
                        break
                
                if self.should_continue():
                    time.sleep(self.interval)
                    
        except KeyboardInterrupt:
            print("\n\n⏹️  用户停止")
        finally:
            print(f"\n📊 统计信息:")
            print(f"   - 总滑动次数: {self.count}")
            print(f"   - 运行时间: {self.count * self.interval} 秒")

def main():
    # 命令行参数解析
    parser = argparse.ArgumentParser(description='手机自动化滑动脚本')
    parser.add_argument('-i', '--interval', type=int, default=5, 
                       help='滑动间隔（秒），默认5秒')
    parser.add_argument('-n', '--count', type=int, default=None,
                       help='滑动次数，不指定则无限循环')
    parser.add_argument('-p', '--package', type=str, default=None,
                       help='应用包名，如：com.ss.android.ugc.aweme（抖音）')
    
    args = parser.parse_args()
    
    # 创建并运行自动化任务
    automation = PhoneAutomation(
        interval=args.interval,
        total_count=args.count,
        app_package=args.package
    )
    automation.run()

if __name__ == "__main__":
    main()